const childProcess = require('child_process')
const vscode = require('vscode');

const base64Encode = (string) => Buffer.from(string).toString('base64')
async function prodLogin(config) {
    if (!config) return

    // 记录登录开始时间
    const startTime = new Date();
    const { domain, loginId, password, url, browser = 'Google Chrome' } = config
    const res = await fetch(`${url}/api/user/sign-in`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            domain,
            loginId,
            password: base64Encode(password)
        })
    })
    .then(res => res.json())
    .catch(e => {
        console.error(e)
    })
    
    // 检查登录响应
    if (!res || !res.uIdToken) {
        // 使用vscode API显示错误消息
        vscode.window.showErrorMessage('登录失败，请检查您的凭据');
        return;
    }
    
    const { uIdToken } = res

    try {
        const fullUrl = `${url}?loginToken=${uIdToken}`
        const command = 'open';
        const cliArguments = ['-a', browser, fullUrl];
        
        // 使用 execFile 替代 spawn，因为它更适合执行单个命令
        childProcess.execFile(command, cliArguments, (error) => {   
            if (error) {
                vscode.window.showErrorMessage(`打开浏览器失败: ${error.message}`);
            }
        });
    } catch (e) {
        vscode.window.showErrorMessage(`打开浏览器失败: ${e.message}`);
    }
}
module.exports = prodLogin